package com.yanqu.road.server.cmd.player;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.connect.ServerLinkControl;
import com.yanqu.road.entity.enums.ePlatformForbiddenType;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.logic.bussiness.player.UserBussiness;
import com.yanqu.road.logic.config.ChannelConfig;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.login.LoginProto;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.command.Command;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.helper.SignHelper;
import com.yanqu.road.server.logic.player.LoginIpManager;
import com.yanqu.road.server.manger.ForbiddenIpMgr;
import com.yanqu.road.server.manger.ForbiddenMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.WhiteListLocationMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.server.webservice.GamePublicFunction;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.string.StringUtils;
import io.netty.channel.ChannelHandlerContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Objects;

@Cmd(code = Protocol.S_AGENT_CHECK_LOGIN, desc = "网关服请求是否允许用户登录")
public class AgentReqLoginCheckCmd implements Command {

	private static Logger logger = LogManager.getLogger(AgentReqLoginCheckCmd.class.getName());

	@Override
	public void execute(ChannelHandlerContext ctx, YanQuMessage packet) throws Exception {
		LoginProto.LoginReqMsg reqMsg = LoginProto.LoginReqMsg.parseFrom(packet.toByteArray());
		long userId = reqMsg.getUserId();
		String ip = LoginIpManager.getUserIp(userId);
		long nowTime = System.currentTimeMillis();

		UserInfo userInfo;
		GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(packet.getPlayerId());
		if (onlinePlayer == null) {
			userInfo = UserBussiness.getUserInfoByUserId(packet.getPlayerId(), reqMsg.getOpenId());
		} else {
			userInfo = onlinePlayer.getUserInfo();
		}

		if (userInfo == null) {
			return;
		}
		//加一层openId校验
		if(!Objects.equals(reqMsg.getOpenId(), userInfo.getOpenId())){
			return;
		}
		//加一个内存检测
		if(0 != GamePublicFunction.loginCheckGameServerMemory(packet.getPlayerId())){
			return;
		}

		GamePlayer player;
		// 判断账号是否被封禁等
		if (ChannelConfig.CHECK_WEBSOCKET == 1 && !SignHelper.checkWebsocketSign(reqMsg.getSign(), packet.getPlayerId(), reqMsg.getOpenId(), UserMgr.getUserSignValue(packet.getPlayerId()))) {
			player = null;
		} else if (!ForbiddenMgr.canLogin(ip) || userInfo.getBlackListEndTime() > System.currentTimeMillis() ||
				ForbiddenMgr.isPlatformForbidden(userInfo.getPlatformUserId(), ePlatformForbiddenType.LOGIN.getType())) {
			player = null;
		} else if (ForbiddenIpMgr.isForbiddenIp(reqMsg.getIp())) {
			player = null;
		} else if (WhiteListLocationMgr.whiteNoSetIpLocation(userId)) {
			player = null;
		} else {
			player = GamePlayerMgr.getPlayer(packet.getPlayerId(), reqMsg.getOpenId());
		}

		logger.info("player login,userId:{},GamePlayerMgr getPlayer use time:{}ms", packet.getPlayerId(), System.currentTimeMillis() - nowTime);
		boolean result = false;
		if (null != player) {
			result = true;
			player.setLanguage(reqMsg.getLangType());          //设置语言
			ip = changeIp(ip);
			player.setIp(ip);
			player.setWebSocketIp(reqMsg.getIp());
			player.setPhonePlatform(reqMsg.getPhonePlatform());
			player.setClientCurVer(reqMsg.getClientVer());
			player.setDeviceId(reqMsg.getDeviceId());
			player.setUserLocation();
			player.setAppId(reqMsg.getAppId());
			player.setChildGameId(reqMsg.getChildGameId());
			player.setLoginLinkType(reqMsg.getLoginLinkType());

			if(reqMsg.hasZfbChannel()){
				player.setZfbChannel(reqMsg.getZfbChannel());
			} else {
			    player.setZfbChannel("");
            }

			JSONObject appExtJson;
			try {
				appExtJson = JSONObject.parseObject(reqMsg.getAppExt());
			} catch (Exception ex) {
				logger.error("appExt exception. : {}", reqMsg.getAppExt(), ex);
				appExtJson = new JSONObject();
			}
			if (appExtJson != null) {
				player.setAppExt(appExtJson);
			}
			//直播搞一下
			if(reqMsg.getLiveShowType() == 1) {//开播了
				player.setLiveShow();
			}
		}
		String clientVersion = reqMsg.getClientVer();
		if(!StringUtils.isNullOrEmpty(clientVersion)) {
			logger.info("player login,userId:{},clientVersion:{}", userId, clientVersion);
		}else {
			logger.info("player login,userId:{},clientVersion is empty", userId);
		}
		LoginProto.LoginResultMsg.Builder checkMsg = LoginProto.LoginResultMsg.newBuilder();
		checkMsg.setUserId(userId);
		checkMsg.setResult(result);
		checkMsg.setLoginToken(reqMsg.getLoginToken());
		YanQuMessage pkg = YanQuMessageUtils.buildMessage(Protocol.A_LOGIN_RESPONSE, checkMsg);
		ServerLinkControl.send(userId, pkg);
	}

	private String changeIp(String ip) {
		if (!StringUtils.isNullOrEmpty(ip)) {
			if (ip.startsWith("/")) {
				ip = ip.substring(1, ip.length() - 1);
				ip = ip.split(":")[0];
			}
		}
		return ip;
	}
}
